package com.leyou.cart.interceptor;

import com.leyou.cart.config.JwtProperties;
import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 登录用户拦截器
 */
@Component
public class UserInterceptor implements HandlerInterceptor{

    @Autowired
    private JwtProperties jwtProps;

    private UserInfo userInfo;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1.服务token校验
        //1）取出服务token
        String appToken = request.getHeader(LyConstants.APP_TOKEN_HEADER);

        //2）校验服务token是否合法
        Payload<AppInfo> appInfoPayload = null;

        try {
            appInfoPayload = JwtUtils.getInfoFromToken(appToken, jwtProps.getPublicKey(), AppInfo.class);
        } catch (Exception e) {
            return false;
        }

        //3）从服务token取出targetList
        //3.1 取出targetList
        AppInfo appInfo = appInfoPayload.getInfo();
        List<String> targetList = appInfo.getTargetList();
        //3.2 取出当前服务名称
        String serviceName = jwtProps.getApp().getServiceName();
        //4）判断当前服务名称是否在targetList中
        if(!targetList.contains(serviceName)){
            return false;
        }

        //2.校验并获取用户token
        Payload<UserInfo> userInfoPayload = null;
        try {
            String token = CookieUtils.getCookieValue(request,jwtProps.getCookie().getCookieName());
            userInfoPayload = JwtUtils.getInfoFromToken(token, jwtProps.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            return false;
        }

        //3.从用户token中取出UserInfo
        UserInfo userInfo = userInfoPayload.getInfo();

        //4.把UserInfo存入ThreadLocal中
        UserHolder.setUser(userInfo);

        //放行
        return true;
    }
}
